package com.jason.controller;

import com.jason.model.entity.User;
import com.jason.model.request.LoginRequest;
import com.jason.service.UserService;
import com.jason.utlis.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("api/v1/pri/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 注册
     * @param userInfo
     * @return
     */
    @PostMapping("/register")
    public JsonData register(@RequestBody Map<String,String> userInfo){
        int rows=userService.save(userInfo);
        return rows==1?JsonData.buildSuccess():JsonData.bulidError("注册失败请重试");
    }

    /**
     * 登录
     * @param loginRequest
     * @return
     */
    @PostMapping("/login")
    public JsonData login(@RequestBody LoginRequest loginRequest){

      String token=userService.findByPhoneAndPwd(loginRequest.getPhone(),loginRequest.getPwd());
        return token==null?JsonData.bulidError("登录失败,账号密码错误"):JsonData.buildSuccess(token);

    }

    /**
     * 根据用户id查询用户信息
     * @param request
     * @return
     */
    @GetMapping("/find_by_token")
    public JsonData findUserInfoByToken(HttpServletRequest request){

        Integer userId = (Integer) request.getAttribute("user_id");
        if (userId==null){
            return JsonData.bulidError("查询失败");
        }
        User user=userService.findByUserId(userId);
        return JsonData.buildSuccess(user);
    }


}
